package com.example.elderlycaresystem.service;

import com.example.elderlycaresystem.entity.User;
import com.example.elderlycaresystem.mapper.UserMapper;
import com.example.elderlycaresystem.util.PasswordEncoderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public int addUser(User user) {
        // 对密码进行加密
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(PasswordEncoderUtil.encodePassword(user.getPassword()));
        }
        return userMapper.insertUser(user);
    }

    public User getUserById(Long id) {
        return userMapper.selectUserById(id);
    }

    public User getUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    public List<User> getAllUsers() {
        return userMapper.selectAllUsers();
    }

    public int updateUser(User user) {
        // 如果提供了新密码，则进行加密
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            // 检查是否与数据库中的密码相同（如果相同则不需要重新加密）
            User existingUser = userMapper.selectUserById(user.getId());
            if (!user.getPassword().equals(existingUser.getPassword())) {
                user.setPassword(PasswordEncoderUtil.encodePassword(user.getPassword()));
            }
        } else {
            // 如果没有提供密码，则保留原密码
            User existingUser = userMapper.selectUserById(user.getId());
            user.setPassword(existingUser.getPassword());
        }
        return userMapper.updateUser(user);
    }

    public int deleteUserById(Long id) {
        return userMapper.deleteUserById(id);
    }

    public User getUserByEmail(String email) {
        return userMapper.selectUserByEmail(email);
    }

    /**
     * 用户登录验证
     * @param username 用户名
     * @param password 密码
     * @return 用户信息，如果验证失败则返回null
     */
    public User login(String username, String password) {
        User user = userMapper.selectUserByUserName(username);
        if (user != null && PasswordEncoderUtil.matches(password, user.getPassword())) {
            // 登录成功，返回用户信息（注意：不要返回密码）
            user.setPassword(null); // 清空密码，避免返回
            return user;
        }
        return null;
    }
}